package com.black.play.component.box;

import com.black.play.common.unit.UnitProvider;
import com.black.play.component.base.AppProgressBar;
import lombok.Getter;
import lombok.Setter;

import javax.swing.*;
import java.awt.*;
import java.util.HashMap;
import java.util.Map;
import java.util.function.Function;

/**
 * @author ylx
 */
@Getter
@Setter
public class AppProgressBarBox<T> extends JDialog
{

    private final Map<T, AppProgressBar> progressManager = new HashMap<>();

    private final GridLayout layout = new GridLayout(progressManager.size(), 2);

    private String speedUnit = null;

    private UnitProvider speedUnitProvider = null;

    public AppProgressBarBox(JFrame parent)
    {
        super(parent, "进度", false);
        this.setLocation(400, 300);
        this.setDefaultCloseOperation(DISPOSE_ON_CLOSE);
        this.setLayout(this.layout);
    }

    public void addProgress(T key, Function<T, String> labelProvider)
    {
        String labelText = labelProvider.apply(key);
        this.setVisible(true);
        if (progressManager.containsKey(key))
            return;
        JLabel label = new JLabel(labelText);
        AppProgressBar progressBar = new AppProgressBar(this);
        progressBar.setSpeedUnitProvider(speedUnitProvider);
        progressBar.setSpeedUnit(speedUnit);
        progressManager.put(key, progressBar);
        this.setSize(800, 100 * progressManager.size());
        this.layout.setRows(progressManager.size());
        this.add(label);
        this.add(progressBar);
    }

    public void initProgress(T key, Number total)
    {
        progressManager.get(key).initProgress(total);
    }

    public void setProgress(T key, Number current)
    {
        AppProgressBar progressBar = progressManager.get(key);
        progressBar.setProgress(current);
    }
}
